package org.jeecg.modules.online.cgform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.components.LinkDown;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.mapper.OnlCgformFieldMapper;
import org.jeecg.modules.online.cgform.mapper.OnlCgformHeadMapper;
import org.jeecg.modules.online.cgform.model.TreeModel;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.util.CgformUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: Online表单开发
 * @Author: jeecg-boot
 * @Date: 2019-03-12
 * @Version: V1.0
 */
@Service("onlCgformFieldServiceImpl")
@Slf4j
public class OnlCgformFieldServiceImpl extends ServiceImpl<OnlCgformFieldMapper, OnlCgformField> implements IOnlCgformFieldService {

	@Autowired
	private OnlCgformFieldMapper onlCgformFieldMapper;

	@Autowired
	private OnlCgformHeadMapper cgformHeadMapper;
	
	/**树形列表根节点父级ID为0*/
	private static final String TREE_ROOT_PID = "0";
	
	@Override
	public Map<String, Object> queryAutolistPage(String tbname, String headId,Map<String,Object> params,List<String> needList) {
		Map<String, Object> result = new HashMap<>();
		
		//1.查询字段集合
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, headId);
		query.orderByAsc(OnlCgformField::getOrderNum);
		List<OnlCgformField> allFieldList = this.list(query);
		
		//2.获取显示列
		List<OnlCgformField> fieldList = this.queryAvailableFields(tbname, true, allFieldList,needList);
		
		//2.获取查询sql
		StringBuffer sb = new StringBuffer();
		//基础SQL
		CgformUtil.getAutoListBaseSql(tbname, fieldList, sb);
		//查询条件（数据权限）
		String conditionSql = CgformUtil.getAutoListConditionSql(allFieldList, params,needList);

		// update-begin---Author:sunjianlei   Date:20191223  for：新增高级查询拼接SQL（支持主子表查询）
		//高级查询器（页面动态选择条件）
		String superQuerySql = CgformUtil.getAutoListSuperQuerySql(params);
		// 拼接条件
		sb.append(CgformUtil.SQL_WHERE_TRUE + conditionSql + superQuerySql);
		// update-end---Author:sunjianlei   Date:20191223  for：新增高级查询拼接SQL（支持主子表查询）

		//排序 判断是否有此字段
		Object columnParam = params.get("column");
		if(columnParam!=null){
			String column = columnParam.toString();
			String order = params.get("order").toString();
			if(hasField(column, allFieldList)) {
				sb.append(CgformUtil.SQL_ORDER+oConvertUtils.camelToUnderline(column));
				if(CgformUtil.SQL_ASC.equals(order)) {
					sb.append(" "+CgformUtil.SQL_ASC);
				}else {
					sb.append(" "+CgformUtil.SQL_DESC);
				}
			}
		}
		//3.分页查询
		Integer pageSize = params.get("pageSize")==null?10:Integer.parseInt(params.get("pageSize").toString());
		if(pageSize==-521) {
			//20190521 for:如果传此参数为-521 则表示不需要分页 直接走简单查询即可
			List<Map<String,Object>> dataList =  this.onlCgformFieldMapper.queryListBySql(sb.toString());
			log.info("---Online查询sql 不分页 :>>"+sb.toString());
			if(dataList==null || dataList.size()==0) {
				result.put("total",0);
				result.put("fieldList",fieldList);
			}else {
				result.put("total",dataList.size());
				result.put("fieldList",fieldList);
				result.put("records",CgformUtil.toLowerCasePageList(dataList));
			}
		}else {
			Integer pageNo = params.get("pageNo")==null?1:Integer.parseInt(params.get("pageNo").toString());
			Page<Map<String,Object>> page = new Page<>(pageNo,pageSize);
			log.info("---Online查询sql:>>"+sb.toString());
			IPage<Map<String,Object>> pageList = this.onlCgformFieldMapper.selectPageBySql(page, sb.toString());

			//4.处理结果 返回需要的数据
			result.put("total",pageList.getTotal());
			result.put("records",CgformUtil.toLowerCasePageList(pageList.getRecords()));
		}
		return result;
	}

	@Override
	public void saveFormData(String code,String tbname, JSONObject json,boolean isCrazy) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		List<OnlCgformField> fieldList = this.list(query);
		if(isCrazy) {
			baseMapper.executeInsertSQL(CgformUtil.getCrazyFormDataSaveSql(tbname, fieldList, json)) ;
		}else {
			baseMapper.executeInsertSQL(CgformUtil.getFormDataSaveSql(tbname, fieldList, json)) ;
		}
	}
	@Override
	public void saveTreeFormData(String code, String tbname, JSONObject json, String hasChildField, String pidField) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		List<OnlCgformField> fieldList = this.list(query);
		for (OnlCgformField item : fieldList) {
			//如果是否有子节点不显示 则新增一个节点时设置为0
			if(hasChildField.equals(item.getDbFieldName()) && item.getIsShowForm()!=1) {
				item.setIsShowForm(1);
				json.put(hasChildField, TREE_ROOT_PID);
				continue;
			}
			//如果父id为空 则设置为0 表示根节点
			if(pidField.equals(item.getDbFieldName()) && oConvertUtils.isEmpty(json.get(pidField))) {
				item.setIsShowForm(1);
				json.put(pidField, TREE_ROOT_PID);
			}
		}
		Map<String,Object> params = CgformUtil.getFormDataSaveSql(tbname, fieldList, json);
		baseMapper.executeInsertSQL(params);
		//保存当前节点时设置父级节点为有子节点
		if(!TREE_ROOT_PID.equals(json.getString(pidField))) {
			baseMapper.editFormData("update "+tbname +" set "+hasChildField+" = '1' where id = '"+json.getString(pidField)+"'");
		}
		
	}
	
	@Override
	public void saveFormData(List<OnlCgformField> fieldList, String tbname, JSONObject json) {
		Map<String,Object> params = CgformUtil.getFormDataSaveSql(tbname, fieldList, json);
		baseMapper.executeInsertSQL(params);
	}

	@Override
	public void editFormData(String code,String tbname, JSONObject json,boolean isCrazy) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		List<OnlCgformField> fieldList =  this.list(query);
		if(isCrazy) {
			baseMapper.executeUpdatetSQL(CgformUtil.getCrazyFormDataEditSql(tbname, fieldList, json)) ;
		}else {
			baseMapper.executeUpdatetSQL(CgformUtil.getFormDataEditSql(tbname, fieldList, json)) ;
		}
	}
	
	@Override
	public void editTreeFormData(String code, String tbname, JSONObject json,String hasChildField, String pidField) {
		//修改原父级节点加先父级节点
		String realTableName = CgformUtil.getRealTableName(tbname);
		String sql = "select * from "+realTableName+" where id = '"+json.getString("id") +"'";
		Map<String,Object> metaData = this.baseMapper.queryFormData(sql);
		//update-begin-author:taoyan date:20190927 for:oracle数据库大小写兼容问题
		Map<String,Object> metaDataLower = CgformUtil.transLowerCaseMapKey(metaData);
		String metaPid = metaDataLower.get(pidField).toString();
		//update-end-author:taoyan date:20190927 for:oracle数据库大小写兼容问题

		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		List<OnlCgformField> fieldList =  this.list(query);
		for (OnlCgformField item : fieldList) {
			//如果父id为空 则设置为0 表示根节点
			if(pidField.equals(item.getDbFieldName()) && oConvertUtils.isEmpty(json.get(pidField))) {
				item.setIsShowForm(1);
				json.put(pidField, TREE_ROOT_PID);
			}
		}
		Map<String,Object> params = CgformUtil.getFormDataEditSql(tbname, fieldList, json);
		//修改本级节点
		baseMapper.executeUpdatetSQL(params);
		
		if(!metaPid.equals(json.getString(pidField))) {
			//如果老数据的父级ID和新数据的父级ID不一致 那么求老数据的父级ID的子节点count
			if(!TREE_ROOT_PID.equals(metaPid)) {
				String countSql = "select count(*) from "+realTableName+" where "+pidField+" = '"+metaPid+"'";
				Integer count = baseMapper.queryCountBySql(countSql);
				if(count==null || count==0) {
					baseMapper.editFormData("update "+realTableName +" set "+hasChildField+" = '0' where id = '"+metaPid+"'");
				}
			}
			//编辑当前节点时设置父级节点为有子节点
			if(!TREE_ROOT_PID.equals(json.getString(pidField))) {
				baseMapper.editFormData("update "+realTableName +" set "+hasChildField+" = '1' where id = '"+json.getString(pidField)+"'");
			}
			
		}
		
	}

	@Override
	public Map<String, Object> queryFormData(String code, String tbname, String id) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		query.eq(OnlCgformField::getIsShowForm,1);
		List<OnlCgformField> fieldList =  this.list(query);
		String sql = CgformUtil.getSelectFormSql(tbname, fieldList, id);
		return onlCgformFieldMapper.queryFormData(sql);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteAutoListMainAndSub(OnlCgformHead head, String ids) {
		if(head.getTableType()==2) {
			String headId = head.getId();
			String headName = head.getTableName();

			String tableName = "tableName"; //子表名key
			String linkField = "linkField";//子表外键字段key
			String linkValueStr = "linkValueStr";//子表外键字段值key(多值，逗号分隔)
			String mainField = "mainField";//子表外键关联主表的字段key
			//外键集合list, 找出 tablename  linkfiled mainField
			List<Map<String, String>> ls = new ArrayList<>();
			//子表数据删除逻辑
			if(oConvertUtils.isNotEmpty(head.getSubTableStr())){
				for (String tbname : head.getSubTableStr().split(",")) {
					//查询子表配置
					OnlCgformHead subTable = cgformHeadMapper.selectOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, tbname));
					if (subTable == null) {
						continue;
					}
					//查询子表配置的外键字段
					LambdaQueryWrapper query = new LambdaQueryWrapper<OnlCgformField>().eq(OnlCgformField::getCgformHeadId, subTable.getId()).eq(OnlCgformField::getMainTable, head.getTableName());
					List<OnlCgformField> subFieldList = this.list(query);
					if (subFieldList == null || subFieldList.size() == 0) {
						continue;
					}
					//TODO 目前外键只支持一个，不支持组合外键
					OnlCgformField subField = subFieldList.get(0);
					Map<String, String> map = new HashMap<>();
					//子表字段名字
					map.put(linkField, subField.getDbFieldName());
					//外键关联的主表字段
					map.put(mainField, subField.getMainField());
					//子表表名
					map.put(tableName, tbname);
					map.put(linkValueStr, "");
					ls.add(map);
				}

				LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
				query.eq(OnlCgformField::getCgformHeadId, headId);
				//查询主表的字段配置
				List<OnlCgformField> fieldList = this.list(query);
				//获取id数组
				String[] idArr = ids.split(CgformUtil.SQL_COMMA);

				for (String  id: idArr) {
					String sql = CgformUtil.getSelectFormSql(headName, fieldList, id);
					//获取主表数据
					Map<String, Object> map = onlCgformFieldMapper.queryFormData(sql);
					List<String> linkValueList = new ArrayList<>();
					for (Map<String, String> temp : ls) {
						Object linkValue = map.get(temp.get(mainField).toLowerCase());
						if(linkValue==null){
							linkValue = map.get(temp.get(mainField).toUpperCase());
						}
						if (linkValue == null) {
							continue;
						}
						String newLinkValue = temp.get(linkValueStr)+String.valueOf(linkValue)+CgformUtil.SQL_COMMA;
						temp.put(linkValueStr,newLinkValue);
					}
				}
				//删除子表数据
				for (Map<String, String> temp : ls) {
					deleteAutoList(temp.get(tableName),temp.get(linkField),temp.get(linkValueStr));
				}
			}
			//删除主表数据
			deleteAutoListById(head.getTableName(), ids);
		}
	}

	@Override
	public void deleteAutoListById(String tbname, String ids) {
		deleteAutoList(tbname, "id", ids);
	}
	
	@Override
	public void deleteAutoList(String tbname, String linkField, String linkValue) {
		if(linkValue!=null && !"".equals(linkValue)){
			String[] arr = linkValue.split(",");
			StringBuffer sb = new StringBuffer();
			for (String str : arr) {
				if(str==null||"".equals(str)) {
					continue;
				}
				sb.append("'"+str+"',");
			}
			String temp = sb.toString();
			String sql = "DELETE FROM "+CgformUtil.getRealTableName(tbname) + " where "+linkField+" in("+temp.substring(0,temp.length()-1)+")";
			log.info("--删除sql-->"+sql);
			this.onlCgformFieldMapper.deleteAutoList(sql);
		}
	}

	@Override
	public List<Map<String, String>> getAutoListQueryInfo(String code) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		query.eq(OnlCgformField::getIsQuery,1);
		query.orderByAsc(OnlCgformField::getOrderNum);
		List<OnlCgformField> fieldList =  this.list(query);
		List<Map<String, String>> list = new ArrayList<>();
		int i=0;
		for (OnlCgformField item : fieldList) {
			Map<String,String> map = new HashMap<>();
			map.put("label",item.getDbFieldTxt());
			map.put("field",item.getDbFieldName());
			map.put("mode",item.getQueryMode());
			if("1".equals(item.getQueryConfigFlag())){
				//自定义查询配置
				map.put("config","1");
				map.put("view",item.getQueryShowType());
				map.put("defValue",item.getQueryDefVal());
				if(CgformUtil.CAT_TREE.equals(item.getFieldShowType())){
					map.put("pcode",item.getQueryDictField());
				}else if(CgformUtil.SEL_TREE.equals(item.getFieldShowType())){
					//ID列,父ID列,显示列,是否有子节点列
					String[] arr = item.getQueryDictText().split(CgformUtil.SQL_COMMA);
					String dict = item.getQueryDictTable()+CgformUtil.SQL_COMMA+arr[2]+CgformUtil.SQL_COMMA+arr[0];
					map.put("dict",dict);
					map.put("pidField",arr[1]);
					map.put("hasChildField",arr[3]);
					map.put("pidValue",item.getQueryDictField());
				}else{
					map.put("dictTable",item.getQueryDictTable());
					map.put("dictCode",item.getQueryDictField());
					map.put("dictText",item.getQueryDictText());
				}
			}else{
				map.put("view",item.getFieldShowType());
				//当  分类字典树控件 需要额外传这三个参数
				if(CgformUtil.CAT_TREE.equals(item.getFieldShowType())){
					map.put("pcode",item.getDictField());
				}
				//当  自定义树tree 需要额外传这三个参数
				else if(CgformUtil.SEL_TREE.equals(item.getFieldShowType())){
					//ID列,父ID列,显示列,是否有子节点列
					String[] arr = item.getDictText().split(CgformUtil.SQL_COMMA);
					String dict = item.getDictTable()+CgformUtil.SQL_COMMA+arr[2]+CgformUtil.SQL_COMMA+arr[0];
					map.put("dict",dict);
					map.put("pidField",arr[1]);
					map.put("hasChildField",arr[3]);
					map.put("pidValue",item.getDictField());
				} else if(CgformUtil.POPUP.equals(item.getFieldShowType())){
					map.put("dictTable",item.getDictTable());
					map.put("dictCode",item.getDictField());
					map.put("dictText",item.getDictText());
				}
				map.put("mode",item.getQueryMode());
			}
			if((++i)>2) {
				map.put("hidden","1");
			}
			list.add(map);
		}
		return list;
	}

	@Override
	public List<OnlCgformField> queryFormFields(String code,boolean isform) {
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, code);
		if(isform) {
			query.eq(OnlCgformField::getIsShowForm,1);
		}
		return this.list(query);
	}

	@Override
	public List<OnlCgformField> queryFormFieldsByTableName(String tableName) {
		OnlCgformHead head = cgformHeadMapper.selectOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, tableName));
		if (head != null) {
			LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<>();
			query.eq(OnlCgformField::getCgformHeadId, head.getId());
			return this.list(query);
		}
		return null;
	}

	@Override
	public OnlCgformField queryFormFieldByTableNameAndField(String tableName, String fieldName) {
		OnlCgformHead head = cgformHeadMapper.selectOne(new LambdaQueryWrapper<OnlCgformHead>().eq(OnlCgformHead::getTableName, tableName));
		if (head != null) {
			LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<>();
			query.eq(OnlCgformField::getCgformHeadId, head.getId());
			query.eq(OnlCgformField::getDbFieldName,fieldName);
			if(this.list(query)!=null && this.list(query).size()>0){
				return this.list(query).get(0);
			}
		}
		return null;
	}

	@Override
	public Map<String, Object> queryFormData(List<OnlCgformField> fieldList, String tbname, String id) {
		String sql = CgformUtil.getSelectFormSql(tbname, fieldList, id);
		return onlCgformFieldMapper.queryFormData(sql);
	}

	@Override
	public List<Map<String, Object>> querySubFormData(List<OnlCgformField> fieldList, String tbname, String linkField,
			String value) {
		String sql = CgformUtil.getSelectSubFormSql(tbname, fieldList, linkField, value);
		return onlCgformFieldMapper.queryListData(sql);
	}

	@Override
	public IPage<Map<String, Object>> selectPageBySql(Page<Map<String, Object>> page, String sql) {
		return this.baseMapper.selectPageBySql(page, sql);
	}

	@Override
	public List<String> selectOnlineHideColumns(String tbname) {
		String onlineTbname = "online:"+tbname+"%";
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		List<String> list = this.baseMapper.selectOnlineHideColumns(userId, onlineTbname);
		return handleRuleString(list);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OnlCgformField> queryAvailableFields(String cgFormId,String tbname,String taskId,boolean isList) {
		
		//1.查询online配置的显示列
		LambdaQueryWrapper<OnlCgformField> query = new LambdaQueryWrapper<OnlCgformField>();
		query.eq(OnlCgformField::getCgformHeadId, cgFormId);
		if(isList) {
			query.eq(OnlCgformField::getIsShowList,1);
		}else {
			query.eq(OnlCgformField::getIsShowForm,1);
		}
		query.orderByAsc(OnlCgformField::getOrderNum);
		List<OnlCgformField> fieldList = this.list(query);
		
		//2.查询角色授权的/菜单配置未授权的隐藏列
		String onlineTbname = "online:"+tbname+"%";
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		List<String> hideColumns = new ArrayList<String>();
		if(oConvertUtils.isEmpty(taskId)){
			List<String> onlineHideConfigColumns = this.baseMapper.selectOnlineHideColumns(userId, onlineTbname);
			if(!(onlineHideConfigColumns==null || onlineHideConfigColumns.size()==0 || onlineHideConfigColumns.get(0)==null)) {
				hideColumns.addAll(onlineHideConfigColumns);
			}
		}else{
			//新增逻辑处理 流程字段权限控制
			if(oConvertUtils.isNotEmpty(taskId)){
				List<String> flowHideConfigColumns = this.baseMapper.selectFlowAuthColumns(tbname,taskId,"1");
				if(flowHideConfigColumns!=null && flowHideConfigColumns.size()>0 && flowHideConfigColumns.get(0)!=null){
					hideColumns.addAll(flowHideConfigColumns);
				}
			}
		}

		//3.过滤list
		if(hideColumns.size()==0){
			return fieldList;
		}
		
		/* jdk8循环效率
		  * 执行效率排序为 ：for > forEach > stream
		  * 开发效率排序为：for < forEach < stream
		  * 大数据量stream的效率会更好，这里没啥大数据 直接选择for
		 */
		List<OnlCgformField> result = new ArrayList<OnlCgformField>();
		//遍历字段集合 判断隐藏列是否包含每个字段 构造新的有效列集合
		for(int i=0;i<fieldList.size();i++) {
			OnlCgformField field = fieldList.get(i);
			if(handleRuleString(field.getDbFieldName(),hideColumns)) {
				result.add(field);
			}
		}
		return result;
	}
	
	@Override
	public List<String> queryDisabledFields(String tbname) {
		String onlineTbname = "online:"+tbname+"%";
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		List<String> disabledColumns = this.baseMapper.selectOnlineDisabledColumns(userId, onlineTbname);
		return handleRuleString(disabledColumns);
	}

	@Override
	public List<String> queryDisabledFields(String tbname, String taskId) {
		if(oConvertUtils.isEmpty(taskId)){
			return null;
		}
		List<String> disabledColumns = this.baseMapper.selectFlowAuthColumns(tbname,taskId,"2");
		return handleRuleString(disabledColumns);
	}

	/**
	 * 处理 online:tableName:filed 这样的字符串集合 返回filed集合
	 * @param columns
	 * @return
	 */
	private List<String> handleRuleString(List<String> columns){
		List<String> result = new ArrayList<String>();
		if(columns==null || columns.size()==0 || columns.get(0)==null) {
			return result;
		}
		for (String combineStr : columns) {
			if(oConvertUtils.isEmpty(combineStr)) {
				continue;
			}
			String fieldName = combineStr.substring(combineStr.lastIndexOf(":")+1);
			if(oConvertUtils.isEmpty(fieldName)) {
				continue;
			}
			result.add(fieldName);
		}
		return result;
	}

	/**
	 * 查询有效的列集合 (online配置为显示+角色授权显示)
	 * @param tbname 表名
	 * @param isList 是否是列表 true为列表字段 ，false为表单字段
	 * @param needList 树结构参数
	 * @return
	 */
	@Override
	public List<OnlCgformField> queryAvailableFields(String tbname,boolean isList,List<OnlCgformField> List,List<String> needList) {
		List<OnlCgformField> result = new ArrayList<OnlCgformField>();
		
		String onlineTbname = "online:"+tbname+"%";
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		List<String> hideColumns = this.baseMapper.selectOnlineHideColumns(userId, onlineTbname);

		//查询是否存在未权限显示的字段
		boolean hasConfig = true;
		if(hideColumns==null || hideColumns.size()==0 || hideColumns.get(0)==null) {
			hasConfig = false;
		}		
		
		for (OnlCgformField item : List) {
			String name = item.getDbFieldName();
			if(needList!=null && needList.contains(name)) {
				item.setIsQuery(1);
				result.add(item);
				continue;
			}

			//根据列表和表单，进行不同逻辑处理（根据字段配置的是否显示）
			if(isList) {
				//列表
				if(item.getIsShowList()!=1) {
					if(oConvertUtils.isNotEmpty(item.getMainTable()) && oConvertUtils.isNotEmpty(item.getMainField())){
						//隐藏的外键字段，需要加入list
						result.add(item);
						continue;
					}else{
						//字段配置隐藏，则跳过
						continue;
					}
				}
			}else {
				//表单
				if(item.getIsShowForm()!=1) {
					//字段配置隐藏，则跳过
					continue;
				}
			}

			//判断控件字段是否授权
			if(hasConfig) {
				if(handleRuleString(name,hideColumns)){
					result.add(item);
				}
			}else {
				result.add(item);
			}
			
		}
		return result;
	}

	/**
	 * 判断 当前filed 是不是在规则(隐藏)字段集合中 如果在则不操作
	 * @param filed
	 * @param ruleColumns
	 * @return
	 */
	private boolean handleRuleString(String filed,List<String> ruleColumns){
		boolean show = true;
		for(int j=0;j<ruleColumns.size();j++) {
			String combineStr = ruleColumns.get(j);
			if(oConvertUtils.isEmpty(combineStr)) {
				continue;
			}
			String ruleField = combineStr.substring(combineStr.lastIndexOf(":")+1);
			if(oConvertUtils.isEmpty(ruleField)) {
				continue;
			}
			if(ruleField.equals(filed)) {
				show = false;
			}
		}
		return show;
	}
	
	/**
	 * 判断字段名称是否真实有效
	 */
	public boolean hasField(String fieldName,List<OnlCgformField> List) {
		boolean flag = false;
		for (OnlCgformField field : List) {
			if(oConvertUtils.camelToUnderline(fieldName).equals(field.getDbFieldName())) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	@Override
	public void executeInsertSQL(Map<String, Object> params) {
		baseMapper.executeInsertSQL(params);
	}

	@Override
	public void executeUpdatetSQL(Map<String, Object> params) {
		baseMapper.executeUpdatetSQL(params);
	}

	@Override
	public List<TreeModel> queryDataListByLinkDown(LinkDown linkDown) {
		return baseMapper.queryDataListByLinkDown(linkDown);
	}

	@Override
	public void updateTreeNodeNoChild(String tableName, String filed, String id) {
		Map<String, Object> params = CgformUtil.getTreeNodeNoChildSql(tableName,filed,id);
		baseMapper.executeUpdatetSQL(params);
	}


}
